package org.lewis.core.tools;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

public abstract class AbstractResTool {
	
	protected final Log LOG=LogFactory.getLog(getClass());
	
	protected final static String CHARSET="utf-8";
	
	protected final static String CONFIGFILENAME="/config.properties";
	
	protected  String[] host;
	
	protected PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
	
	protected void init(String key){
		synchronized (propertiesPersister) {
			Properties props = new Properties();
			InputStream is = this.getClass().getResourceAsStream(CONFIGFILENAME);
			try {
				propertiesPersister.load(props, new InputStreamReader(is,CHARSET));
			} catch (IOException e) {
				e.printStackTrace();
				LOG.error(e);
			}finally{
				IOUtils.closeQuietly(is);
			}
			String config=props.getProperty(key);
			host=config.split(",");
		}
	}
	
	protected  String getHost(String name){
		int hashcode = Math.abs(name.hashCode());
		int i = (hashcode)%(host.length);
		return host[i];
	}
	


}
